package lumis.portal.monitor.impl;

import java.util.Map;

import org.apache.log4j.MDC;

/**
 * Helper class for MDC manipulation.
 * 
 * @version $Revision: 11804 $ $Date: 2010-07-29 10:06:21 -0300 (Thu, 29 Jul 2010) $
 * @since 5.6.0
 */
class MDCUtil
{
	/**
	 * Puts a key-value pair in current MDC context.
	 * 
	 * @param key
	 *            The key being inserted
	 * @param value
	 *            The value being inserted
	 * @since 5.6.0
	 */
	static void put(String key, String value)
	{
		if (key != null)
		{
			String convertedKey = convertLumisParameter(key);
			if (value != null)
				MDC.put(convertedKey, value);
			else
			{
				Map<?, ?> context = getContext();
				if (context != null)
				{
					MDC.remove(convertedKey);
				}
			}
		}
	}

	/**
	 * Removes an aggregation key from current MDC context.
	 * 
	 * @param key
	 *            The key beign deleted
	 * @since 5.6.0
	 */
	static void remove(String key)
	{
		if (key != null)
		{
			String convertedKey = convertLumisParameter(key);
			Map<?, ?> context = getContext();
			if (context != null)
			{
				MDC.remove(convertedKey);
			}
		}
	}

	/**
	 * Clears current MDC context.
	 * 
	 * @since 5.6.0
	 */
	static void clear()
	{
		Map<?, ?> context = getContext();
		if (context != null)
			context.clear();
	}

	/**
	 * Returns current MDC context.
	 * 
	 * @return current MDC context.
	 * @since 5.6.0
	 */
	private static Map<?, ?> getContext()
	{
		return MDC.getContext();
	}

	/**
	 * Converts keys starting with "lumis.portal.monitor.at" so that they starts
	 * with "lumis".
	 * 
	 * @param key
	 *            the key to be converted
	 * @return the key after conversion
	 * @since 5.6.0
	 */
	private static String convertLumisParameter(String key)
	{
		if (key.startsWith("lumis.portal.monitor.at"))
			key = "lumis" + key.substring(23, key.length());
		return key;
	}
}
